package com.msblearn.C_006;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.locks.Lock;

public class T004_NotifyFreeLock {
    //ArrayList是线程不安全的。
    volatile List list = new ArrayList();
//    volatile  List list = Collections.synchronizedList(new LinkedList<>());

    public void add(Object o) {
        list.add(o);
    }

    public int size() {
        return list.size();
    }

    public static void main(String[] args) {
        T004_NotifyFreeLock holdingLock = new T004_NotifyFreeLock();
        final Object o = new Object();
        //先启动t2,在启动t1
        new Thread(() -> {
            synchronized (o) {
                System.out.println("T2启动");

                if (holdingLock.size() != 5) {
                    try {
                        o.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.println("t2 结束");
                //唤醒t1线程继续执行。
                o.notify();

            }
        }, "T2").start();
        new Thread(() -> {
            System.out.println("t1启动");
            synchronized (o) {
                for (int i = 0; i < 10; i++) {
                    holdingLock.add("add" + i);
                    System.out.println("add" + i);
                    if (holdingLock.size() == 5) {
                        //唤醒t2
                        o.notify();
                        //释放锁，然后t1进入等待
                        try {
                            o.wait();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }

                }
            }

        }, "t1").start();
    }
}
